package com.itmk.web.patrol.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itmk.web.patrol.entity.PatrolTask;
import com.itmk.web.patrol.mapper.PatrolTaskMapper;
import com.itmk.web.patrol.service.PatrolTaskService;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

@Service
public class PatrolTaskServiceImpl extends ServiceImpl<PatrolTaskMapper, PatrolTask> implements PatrolTaskService {

    @Override
    public IPage<PatrolTask> getPageList(Page<PatrolTask> page,  String taskContent, String status) {
        LambdaQueryWrapper<PatrolTask> queryWrapper = new LambdaQueryWrapper<>();

        // 使用Lambda表达式，避免硬编码字段名
        if (StringUtils.isNotBlank(taskContent)) {
            queryWrapper.like(PatrolTask::getTaskContent, taskContent);
        }

        if (StringUtils.isNotBlank(status)) {
            queryWrapper.eq(PatrolTask::getStatus, status);
        }

        return this.page(page, queryWrapper);
    }

    @Override
    public PatrolTask getById(Long id) {
        return baseMapper.selectById(id);
    }

    @Override
    public boolean save(PatrolTask patrolTask) {
        // 确保必要的字段都有值
        if (patrolTask.getSecurityName() == null) {
            throw new IllegalArgumentException("负责保安姓名不能为空");
        }

        if (patrolTask.getTaskContent() == null) {
            throw new IllegalArgumentException("巡逻内容不能为空");
        }

        if (patrolTask.getPatrolAddress() == null) {
            throw new IllegalArgumentException("巡逻地点不能为空");
        }

        if (patrolTask.getPatrolTime() == null) {
            throw new IllegalArgumentException("计划巡逻时间不能为空");
        }


        patrolTask.setCreateTime(LocalDateTime.now());
        patrolTask.setUpdateTime(LocalDateTime.now());
        return baseMapper.insert(patrolTask) > 0;
    }

    @Override
    public boolean updateById(PatrolTask patrolTask) {
        patrolTask.setUpdateTime(LocalDateTime.now());
        return baseMapper.updateById(patrolTask) > 0;
    }

    @Override
    public boolean removeById(Long id) {
        return baseMapper.deleteById(id) > 0;
    }

    @Override
    public boolean updateStatus(Long id, String status) {
        PatrolTask patrolTask = new PatrolTask();
        patrolTask.setTaskId(id);
        patrolTask.setStatus(status);
        patrolTask.setUpdateTime(LocalDateTime.now());
        return baseMapper.updateById(patrolTask) > 0;
    }
}